package com.goodboys.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.URLEncoder;

/**
 * Created by CJ on 2018-05-22.
 */
public class QiniuUtils {

    public static String accessKey ="Mju2MAqifZDqY6vHNgxONrSiFJME7zD9g_-e0TTv";

    public static String secretKey = "FKDYyWEB7VCSD7zy9aDRbOe3V0DHtcx4CQjBCkDd";

    public static String bucket = "file";

    //将将流文件上传到七牛云，返回永久链接
    public static String uploadCloud(InputStream in,String filename) throws QiniuException {
        String url = null;
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket,null,3600,new StringMap()
                .putNotEmpty("saveKey",filename),true);
//            Response response = uploadManager.put(localFilePath, key, upToken);
        Response response = uploadManager.put(in, key, upToken, null, null);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        url = "http://file.usts.top/"+filename;
        return  url;
    }

    public static void main(String[] args) {
        try (InputStream in = new FileInputStream("F://ddd.txt")) {
            String s = QiniuUtils.uploadCloud(in,"ddd.txt");
            System.out.println(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
